using FtpDownloader.Models;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Globalization;

namespace FtpDownloader.Services
{
    public class ScheduledTaskService : BackgroundService
    {
        private readonly FtpDownloadService _ftpDownloadService;
        private readonly ScheduleSettings _scheduleSettings;
        private readonly ILogger<ScheduledTaskService> _logger;
        private Timer? _timer;

        public ScheduledTaskService(
            FtpDownloadService ftpDownloadService,
            IOptions<ScheduleSettings> scheduleSettings,
            ILogger<ScheduledTaskService> logger)
        {
            _ftpDownloadService = ftpDownloadService;
            _scheduleSettings = scheduleSettings.Value;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (!_scheduleSettings.Enabled)
            {
                _logger.LogInformation("定时任务已禁用");
                return;
            }

            _logger.LogInformation("启动定时任务服务...");

            // 计算下次执行时间
            var nextRunTime = CalculateNextRunTime();
            var delay = nextRunTime - DateTime.Now;

            if (delay.TotalMilliseconds > 0)
            {
                _logger.LogInformation("下次执行时间: {NextRunTime}", nextRunTime);
                await Task.Delay(delay, stoppingToken);
            }

            // 创建定时器
            _timer = new Timer(async _ => await ExecuteDownloadTask(), null, TimeSpan.Zero, TimeSpan.FromHours(_scheduleSettings.IntervalHours));

            // 等待取消信号
            await Task.Delay(Timeout.Infinite, stoppingToken);
        }

        private async Task ExecuteDownloadTask()
        {
            try
            {
                _logger.LogInformation("---------------------------------------------------");
                _logger.LogInformation("执行定时下载任务 - {Time}", DateTime.Now);
                await _ftpDownloadService.DownloadFilesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行定时下载任务时发生错误");
            }
        }

        private DateTime CalculateNextRunTime()
        {
            var now = DateTime.Now;
            var timeZone = TimeZoneInfo.FindSystemTimeZoneById(_scheduleSettings.TimeZone);
            var localTime = TimeZoneInfo.ConvertTimeFromUtc(now.ToUniversalTime(), timeZone);

            if (TimeSpan.TryParseExact(_scheduleSettings.StartTime, @"hh\:mm", CultureInfo.InvariantCulture, out var startTime))
            {
                var nextRun = localTime.Date.Add(startTime);
                
                // 如果今天的开始时间已过，则安排到明天
                if (nextRun <= localTime)
                {
                    nextRun = nextRun.AddDays(1);
                }

                return TimeZoneInfo.ConvertTimeToUtc(nextRun, timeZone);
            }

            // 如果解析失败，默认从现在开始
            return now.AddHours(_scheduleSettings.IntervalHours);
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("停止定时任务服务...");
            _timer?.Dispose();
            await base.StopAsync(cancellationToken);
        }
    }
}

